<template>
	<main-container class="coupon-container">
		<div class="coupon-info">
			<el-form
				ref="formRef"
				class="form"
				:model="state.form"
				label-width="140px"
				:rules="state.rules"
				status-icon
				label-position="left"
				v-loading="loading"
			>
				<el-card class="box-card">
					<template #header>
						<div class="card-header">
							<span>{{ state.form.id ? '修改优惠券' : '新增优惠券' }}</span>
						</div>
					</template>
					<el-form-item label="店铺" prop="shopId">
						<select-shop
							ref="selectShopRef"
							:disabled="!!state.form.id"
							:defaultShop="true"
							v-model="state.form.shopId"
							@shopChange="shopChange"
						></select-shop>
					</el-form-item>
					<el-form-item label="优惠券名称" prop="couponName">
						<el-input v-model="state.form.couponName" maxlength="50" show-word-limit></el-input>
					</el-form-item>
					<el-form-item label="有效时间" prop="datatimes">
						<el-date-picker
							v-model="state.form.datatimes"
							:disabled="state.form.id"
							type="datetimerange"
							range-separator="-"
							start-placeholder="活动开始时间"
							end-placeholder="活动结束时间"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
					<el-form-item label="优惠形式" prop="couponType">
						<el-radio-group v-model="state.form.couponType" :disabled="state.form.id">
							<el-radio label="1">指定金额</el-radio>
							<el-radio label="2">折扣</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="优惠金额" prop="amount" v-if="state.form.couponType == '1'">
						<el-input-number v-model="state.form.amount" :disabled="state.form.id" :min="0.01" :precision="2" :controls="false" />
					</el-form-item>
					<el-form-item label="折扣" prop="discount" v-if="state.form.couponType == '2'">
						<el-input-number v-model="state.form.discount" :disabled="state.form.id" :min="0.1" :max="9.9" :precision="1" :controls="false" />
					</el-form-item>
					<el-form-item label="使用门槛" prop="threshold">
						<div style="display: flex">
							<span style="padding: 0px 8px">满：</span>
							<el-input-number v-model="state.form.threshold" :disabled="state.form.id" :precision="2" :controls="false"></el-input-number>
							<span style="padding: 0px 8px; width: 120px">可以使用</span>
						</div>
						<div>
							<p style="color: #f56c6c">0元表示无门槛</p>
						</div>
					</el-form-item>
					<el-form-item label="发行数量" prop="totalNum">
						<el-input-number v-model="state.form.totalNum" :disabled="state.form.id" :min="1" :precision="0" :controls="false" />
					</el-form-item>
					<el-form-item label="领取限制" prop="receiveCount">
						<div style="display: flex">
							<span style="padding: 0px 8px; width: 120px">每人限领：</span>
							<el-input-number v-model="state.form.receiveCount" :disabled="state.form.id" :precision="0" :controls="false" />
							<span style="padding: 0px 8px; width: 120px">张</span>
						</div>
					</el-form-item>
					<el-form-item label="使用说明" prop="useDescription">
						<el-input v-model="state.form.useDescription" maxlength="100" placeholder="请输入使用范围" show-word-limit type="textarea" />
					</el-form-item>
					<el-form-item label="可用范围" prop="useRange">
						<el-radio-group v-model="state.form.useRange" :disabled="state.form.id">
							<el-radio label="1">全部商品</el-radio>
							<el-radio label="2">指定商品</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="指定商品" prop="spuId" v-if="state.form.useRange == '2'">
						<el-button type="success" v-if="!state.form.id" link @click="selectSpu">选择商品</el-button>
						<el-table v-if="state.form.couponGoodsList" :data="state.form.couponGoodsList" style="width: 100%">
							<el-table-column prop="spuUrls" label="图片" width="300">
								<template #default="scope">
									<el-image
										style="width: 50px; height: 50px"
										:src="scope.row.spuUrls[0]"
										:preview-src-list="scope.row.spuUrls"
										fit="cover"
										:preview-teleported="true"
									></el-image>
								</template>
							</el-table-column>
							<el-table-column prop="spuName" label="商品名" show-overflow-tooltip />
							<el-table-column label="操作" width="200" align="center">
								<template #default="scope">
									<el-button :disabled="state.form.id" link type="danger" icon="delete" @click="del(scope.row.id, scope.row.index)"> 删除 </el-button>
								</template>
							</el-table-column>
						</el-table>

						<SelectGoods ref="selectGoods" :limitNum="10" :shopId="state.form.shopId" @currentRow="spuCurrent"></SelectGoods>
					</el-form-item>
					<el-form-item label="启用状态" prop="status">
						<el-radio-group v-model="state.form.status">
							<el-radio v-for="item in status" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-card>
			</el-form>
			<div class="coupon-footer">
				<div class="button">
					<el-button @click="handleClose">关 闭</el-button>
					<el-button type="primary" :disabled="loading" @click="submitForm(formRef)">确 认</el-button>
				</div>
			</div>
		</div>
	</main-container>
</template>
<script lang="ts" setup>
import { defineAsyncComponent, ref, reactive } from 'vue';
import { addObj, editObj, getById } from '/@/api/promotion/couponinfo';
import { getByIds } from '/@/api/product/goodsspu';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, FormInstance } from 'element-plus';
import { useDict } from '/@/utils/dict';
const SelectGoods = defineAsyncComponent(() => import('/@/components/selectGoods/index.vue'));
const SelectShop = defineAsyncComponent(() => import('/@/components/selectShop/index.vue'));
interface DataState {
	form: {
		id: string | undefined;
		couponName: string;
		status: string;
		useRange: string;
		amount: number;
		discount: number;
		threshold: number;
		totalNum: number;
		receiveCount: number;
		useDescription: string;
		datatimes: Array<any>;
		couponType: string;
		couponGoodsList: Array<any>;
		receiveStartedAt: string;
		receiveEndedAt: string;
		shopId: string;
	};
	rules: any;
}
// 字典
const { status } = useDict('status');
const state = reactive<DataState>({
	form: {
		id: undefined,
		couponName: '',
		status: '',
		useRange: '',
		amount: 0,
		discount: 0,
		threshold: 0,
		totalNum: 0,
		receiveCount: 0,
		useDescription: '',
		datatimes: [],
		couponType: '1',
		couponGoodsList: [],
		receiveStartedAt: '',
		receiveEndedAt: '',
		shopId: '',
	},
	rules: {
		couponName: [
			{
				required: true,
				message: '请输入优惠券名称',
				trigger: 'change',
			},
		],
		status: [
			{
				required: true,
				message: '请选择优惠券状态',
				trigger: 'change',
			},
		],

		datatimes: [
			{
				required: true,
				message: '请选择有效时间',
				trigger: 'change',
			},
		],
		couponType: [
			{
				required: true,
				message: '请选择优惠形式',
				trigger: 'change',
			},
		],
		discount: [
			{
				required: true,
				message: '请输入折扣',
				trigger: 'change',
			},
		],
		amount: [
			{
				required: true,
				message: '请输入优惠金额（元）',
				trigger: 'change',
			},
		],
		threshold: [
			{
				required: true,
				message: '请输入使用门槛（元）',
				trigger: 'change',
			},
		],
		totalCount: [
			{
				required: true,
				message: '请输入发行数量',
				trigger: 'change',
			},
		],
		useRange: [
			{
				required: true,
				message: '请选择可用范围',
				trigger: 'change',
			},
		],
		useDescription: [
			{
				required: true,
				message: '请输入使用说明',
				trigger: 'change',
			},
		],
	},
});
const selectGoods = ref();
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const formRef = ref();
/**
 * 关闭事件
 */
const handleClose = () => {
	resetForm(formRef.value);
	router.back();
};
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.form.id = undefined;
	loading.value = false;
	formEl.resetFields();
};
/**
 * 提交按钮
 */
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			state.form.receiveStartedAt = state.form.datatimes[0];
			state.form.receiveEndedAt = state.form.datatimes[1];
			loading.value = true;
			if (state.form.id) {
				//修改
				edit();
			} else {
				//新增
				add();
			}
		}
	});
};
/**
 * 新增
 */
const add = () => {
	addObj(state.form)
		.then(() => {
			ElMessageBox.confirm('新增成功', '提示', {
				confirmButtonText: '继续添加',
				cancelButtonText: '返回列表',
				type: 'success',
			})
				.then(() => {
					resetForm(formRef.value);
				})
				.catch(() => {
					handleClose();
				});
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 修改
 */
const edit = () => {
	editObj(state.form)
		.then(() => {
			ElMessageBox.confirm('修改成功', '提示', {
				confirmButtonText: '新增商品',
				cancelButtonText: '返回列表',
				type: 'success',
			})
				.then(() => {
					resetForm(formRef.value);
				})
				.catch(() => {
					handleClose();
				});
		})
		.catch(() => {
			loading.value = false;
		});
};
const initForm = () => {
	const { id }: any = route.query;
	if (id) {
		getDetail(id);
	}
};
const getDetail = (id: string) => {
	loading.value = true;
	// 修改
	getById(id)
		.then((response) => {
			loading.value = false;
			state.form = response.data.data;
			state.form.datatimes = [state.form.receiveStartedAt, state.form.receiveEndedAt];
			if (state.form.useRange == '2') {
				// 指定商品查询
				const spuIds = state.form.couponGoodsList.map((v) => v.spuId);
				getByIds(spuIds).then((res) => {
					const spuList = res.data.data;
					state.form.couponGoodsList.forEach((v) => {
						const spu = spuList.find((obj: any) => obj.id === v.spuId);
						if (spu) {
							v.spuUrls = spu.spuUrls;
							v.spuName = spu.name;
						}
					});
				});
			}
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 选择商品
 */
const selectSpu = () => {
	selectGoods.value.initPage();
};
/**
 * 删除
 * @param id
 */
const del = (id: string, index: number) => {
	state.form.couponGoodsList.splice(index, 1);
};
const spuCurrent = (spuList: any) => {
	if (spuList) {
		let goodsSpuList: Array<any> = [];
		spuList.forEach((item: any) => {
			goodsSpuList.push({
				spuId: item.id,
				spuName: item.name,
				spuUrls: item.spuUrls,
			});
		});
		state.form.couponGoodsList = goodsSpuList;
	}
};
const shopChange = () => {
	// 清空指定商品
	state.form.couponGoodsList = [];
};

initForm();
</script>
<style lang="scss" scoped>
.coupon-container {
	height: 100%;
	.coupon-info {
		flex: 1;
		overflow: auto;
		.form {
			margin-bottom: 38px;
		}
		.coupon-footer {
			position: absolute;
			bottom: 20px;
			left: 20px;
			right: 20px;
			background-color: #fff;
			border-top: 1px solid var(--next-color-danger-lighter);
			padding: 10px 16px;
			z-index: 9;
			display: flex;
			justify-content: center;
			align-items: center;
			.el-button {
				width: 100px;
			}
			.button {
				display: flex;
				justify-content: center;
			}
		}
	}
}
</style>
